<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/lib/jApiController.php';

class GeoModelEdit extends jApiControllerEdit{

	public function storeSearch($id,$text){
	  $sql='REPLACE INTO search SET s_key_obj=:id, s_ln=:ln, s_text=:text, s_obj_typ=:ch2';
	  $sql_prm=array(':id'=>$id,':ln'=>$this->api->lang,':text'=>$text,':ch2'=>substr($id, 0, 2)  );

		$this->setData($sql, $sql_prm);
		return $rs;
	}
	
	public function getValid(){
		include_once $_SERVER['DOCUMENT_ROOT'].'/lib/GeoValidator.php';
		return GeoValidator::inst($this);
	}
	
	protected function getMaps(){
		include_once $_SERVER['DOCUMENT_ROOT'].'/lib/Map.php';
		return Map::inst($this);
	}
	protected function getFoursquare(){
		include_once $_SERVER['DOCUMENT_ROOT'].'/lib/Foursquare.php';
		return Foursquare::inst($this);
	}
	protected function getDetectLang(){
		include_once $_SERVER['DOCUMENT_ROOT'].'/lib/DetectLang.php';
		return DetectLang::inst($this);
	}

	public function getRegId($name){
		return 'rg'.md5( translit($name) );
	}
	public function getCitId($name){
		return 'ct'.md5( translit($name) );
	}
	public function getUaId($name){
		return 'ub'.md5( translit($name) );
	}
	public function getNetId($name){
		return 'nt'.md5( translitId( mb_strtolower($name, 'utf8') ) );
	}
	
	public function getPntId($name,$lat,$lng){
		$t=explode('.', $lat); $lat=$t[0].'.'.substr($t[1], 0, 6);
		$t=explode('.', $lng); $lng=$t[0].'.'.substr($t[1], 0, 6);
		$name=translit(netNormalName($name));
		return 'pt'.md5($name.$lat.'_'.$lng);
	}
	
	public function postCountry($data=array()){
		if(empty($data)) $data=$this->api->env['_POST'];

	  $fields=array();$vals=array();$fieldsLn=array();$valsLn=array();
    $model=array(
      'ctr_id'=>false,
			'ctr_sysname'=>false,
			'ctr_lang'=>false,
			'ctr_cur'=>false,
			'ctr_geometry'=>false,
		);
		$modelLn=array(
		  'ctr_key'=>false,
		  'ctr_name'=>false,
		  'ln'=>$this->api->lang,
		);
		//Добавление

	  if( empty($data['ctr_id']) ){
	    $mode='insert';

	    if( empty($data['ctr_name']) )
				return $this->error('ctr_name expected'); //
				//throw_error('ctr_name expected',500);

	    //Получаю по системному языку
	    $googleInfo=$this->getMaps()->geocode( array('addr'=>$data['ctr_name'], 'lang'=>'en') );
	    if( !$googleInfo )
				return $this->error($this->getMaps()->getError());

			if( empty($googleInfo['countryIso']) )
				return $this->error('Country name error');

			//Есть ли уже такая страна
			$tst_ctr=$this->makeGet('/country/'.$googleInfo['countryIso'],true);

			if(!empty($tst_ctr)){
			  //Есть страна
			  if(!empty($tst_ctr['ctr_name'])) return array('result'=>'fail','info'=>'Country alredy exists','model'=>$tst_ctr);
			  $sql="UPDATE country SET {fields} WHERE ctr_id=:ctr_id";
			}else{
			  $sql="INSERT INTO country SET {fields} ";
			  //Нет страны
			}

			//Получаю по текщему языку
			if($this->api->lang=='en' || !$translateted=getTranslate()->translate( $googleInfo['country'],'en',$this->api->lang )){
			  $translateted=$googleInfo['country'];
			}

			$data['ctr_name']=$translateted;
			$data['ctr_sysname']=$googleInfo['country'];
			$data['ctr_key']=$data['ctr_id']=$googleInfo['countryIso'];
	    $data['ctr_geometry']=$googleInfo['geometry'];

	    if( !$this->getValid()->country($data) )
				return $this->error('Country model validation error');
				//throw_error('country model validation error',400);

	    $sqlLn="INSERT INTO country_name SET ctr_key=:ctr_key, ctr_name=:ctr_name, ctr_ln=:ln ";
	  //Редактирование
		}else{
		  if( strlen($data['ctr_id'])!=2 )
	      //throw_error('Only country ID expected',500);
				return $this->error('Only region ID expected');

		  $mode='update';
	    $modelBase=$this->makeGet('/country/'. $data['ctr_id']);

	    unset($model['ctr_id'],$model['ctr_sysname']);

	    foreach($modelBase as $k=>$v){
	      if(isset($model[$k])) $model[$k]=$v;
	      if(isset($modelLn[$k])) $modelLn[$k]=$v;
			}

			$sql="UPDATE country SET {fields} WHERE ctr_id=:ctr_id";
			$sqlLn="REPLACE INTO country_name SET ctr_name=:ctr_name ,ctr_key=:ctr_key , ctr_ln=:ln ";
			$vals[':ctr_id']=$data['ctr_id'];
		}

		$data['ctr_key']=$data['ctr_id'];

		if(!empty($sql)){
		  foreach($model as $k=>$v){
				$fields[]=$k.'=:'.$k;
		    $vals[':'.$k]=(isset($data[$k]))?$data[$k]:$v;
			}
			$sql=str_replace('{fields}',implode(',', $fields),$sql);
		  $this->setData($sql, $vals);
		}

		foreach($modelLn as $k=>$v){
			$fieldsLn[]=$k.'=:'.$k;
	    $valsLn[':'.$k]=(isset($data[$k]))?$data[$k]:$v;;
		}
	  $sqlLn=str_replace('{fields}',implode(',', $fieldsLn),$sqlLn);

	  $this->setData($sqlLn, $valsLn);

	  $model=array_merge($model,$modelLn, $data);

    $text=$model['ctr_sysname'].' '.$model['ctr_name'];

//echo 'COUNTRY<pre class="debug">'.print_r ( $model ,true).'</pre>';
    $this->storeSearch($model['ctr_id'], $text);

	  return array('result'=>'success','info'=>'','model'=>$model);
	}

	public function postRegion($data=array()){
	  if(empty($data)) $data=$this->api->env['_POST'];;
	  
		$fields=array();$vals=array();$fieldsLn=array();$valsLn=array();
		$model=array(
		  'reg_id'=>false,
		  'reg_sysname'=>false,
		  'reg_key_ctr'=>false,
		  'reg_geometry'=>false,
		);
		$modelLn=array(
		  'reg_key'=>false,
		  'reg_ch1'=>false,
		  'reg_name'=>false,
		  'reg_ln'=>$this->api->lang,
		);

  	//Редактирование
		if( !empty($data['reg_id']) ){
		  if(substr($data['reg_id'], 0, 2)!='rg')
				return $this->error('Only region ID expected');
				//throw_error('Only region ID expected',500);
		  $mode='update';
	    $modelBase=$this->makeGet('/region/'. $data['reg_id'] );
			
			//Если нет такого региона
	    if(	empty($modelBase) )	unset($data['reg_id'],$modelBase);
	    else{
		    $modelBase['reg_key']=$modelBase['reg_id'];
		    foreach($modelBase as $k=>$v){
		      if(isset($modelLn[$k])) $modelLn[$k]=$v;
				}
				$sql=false;
	      $sqlLn="REPLACE INTO region_name SET reg_key=:reg_key, reg_name=:reg_name, reg_ln=:reg_ln, reg_ch1=:reg_ch1";
				$valsLn[':reg_key']=$data['reg_id'];
			}
		}
		
		//Добавление
	  if( empty($data['reg_id']) ){
	    $mode='insert';

	    if( empty($data['reg_name']) )
				//throw_error('Post region: reg_name expected',500);
				return $this->error('Post region: reg_name expected');
	    
	    //Прогоняю через гугл EN
	    $req=$data;
	    $req['addr']=$data['reg_name'];
	    $req['lang']='en';
	    if((!empty($data['ctr_id']))) $req['country']=$data['ctr_id'];

	    if( !$googleInfo=$this->getMaps()->geocode( $req ) )
				return $this->error($this->getMaps()->getError());
        //throw_error($this->getMaps()->getError(),500);
        
			if(empty( $googleInfo['region'] )) //return $this->error('Region name error'); //
				//throw_error('Region name error',500);
				return $this->error('Region name error');
			
			$data['reg_sysname']=$googleInfo['region'];
			//'rg'.md5($googleInfo['region'])
			$data['reg_id']=$this->getRegId( $googleInfo['region'] );
			
      //Ищу в базе существующее
			$tst=$this->makeGet('/region/'.$data['reg_id']);
			if(!empty($tst)){
			  //Уже есть в БД
			  if(!empty($tst['reg_name'])){
			  		return array('result'=>'fail','info'=>'Region alredy exists','model'=>$tst);
				}
				
			  $sql=false;
			}else{
			  //Нету в БД
			  $sql="INSERT INTO region SET {fields} ";
			}

			if( !$tst=$this->postCountry(array('ctr_name'=>$googleInfo['country']))  )
				return $this->error('Error create country "'.$googleInfo['country'].'"');
				//throw_error('Error create country "'.$googleInfo['country'].'"',400);
			if( empty($tst['model']) )
				return $this->error('Error create country "'.$googleInfo['country'].'"');
				//throw_error('Error create country "'.$googleInfo['country'].'"',400);
			$country=$tst['model'];

	    //Получаю по текщему языку
	    if($this->api->lang=='en' || !$translateted=getTranslate()->translate( $googleInfo['region'],'en',$this->api->lang )){
			  $translateted=$googleInfo['region'];
			}

			$data['reg_key_ctr']=$country['ctr_id'];
			$data['reg_name']=$translateted;

	    $data['reg_geometry']=$googleInfo['geometry'];

	    if( !$this->getValid()->region($data) ){
	      //echo '<pre>',print_r( $data, true),'</pre>';
	      //echo '<pre>',print_r( $this->getValid()->getErrors(), true),'</pre>';
	      return $this->error('region model validation error');
	      //throw_error('region model validation error',400);
			}
	    $sqlLn="REPLACE INTO region_name SET {fields} ";
		}
		
		$data['reg_ch1']=mb_substr($data['reg_name'],0, 1,'utf8');
		$data['reg_key']=$data['reg_id'];

		if($sql){
		  foreach($model as $k=>$v){
				$fields[]=$k.'=:'.$k;
		    $vals[':'.$k]=(isset($data[$k]))?$data[$k]:$v;
			}

			$sql=str_replace('{fields}',implode(',', $fields),$sql);
		  $this->setData($sql, $vals);
		}
		
	  foreach($modelLn as $k=>$v){
			$fieldsLn[]=$k.'=:'.$k;
	    $valsLn[':'.$k]=(isset($data[$k]))?$data[$k]:$v;
		}

		$sqlLn=str_replace('{fields}',implode(',', $fieldsLn),$sqlLn);
		$this->setData($sqlLn, $valsLn);

	  //$model=array_merge($model, $modelLn, $data);
	  $model=$this->makeGet('/region/'.$data['reg_id']);

    $text=$model['ctr_sysname'].' '.$model['ctr_name'].' '.$model['reg_sysname'].' '.$model['reg_name'];
//echo 'REGION<pre class="debug">'.print_r ( $model ,true).'</pre>';
    $this->storeSearch($model['reg_id'], $text);

	  return array('result'=>'success','info'=>'','model'=>$model);
	}
	
	public function postCity($data=array()){
	  if(empty($data)) $data=$this->api->env['_POST'];;
	  
		$fields=array();$vals=array();$fieldsLn=array();$valsLn=array();
    $model=array(
      'cit_id'=>'',
			'cit_sysname'=>'',
			'cit_key_ctr'=>'',
			'cit_key_reg'=>'',
		);
		$modelLn=array(
			'cit_key'=>'',
			'cit_name'=>'',
			'cit_ln'=>$this->api->lang,
		);

		//Редактирование
		if( !empty($data['cit_id']) ){
		  //if( !$this->maskID($data['cit_id'],'city') )
		  if(substr($data['cit_id'], 0, 2)!='ct') //return $this->error('Only city ID expected');
        //throw_error('Only city ID expected',500);
        return $this->error('Only city ID expected');
			
		  $mode='update';
	    $modelBase=$this->makeGet('/city/'. $data['cit_id'] );

			//Если нет такого решиона
	    if(	empty($modelBase)	) unset($data['cit_id'],$modelBase);
	    else{
	      $modelBase['cit_key']=$modelBase['cit_id'];
	      foreach($modelBase as $k=>$v){
		      if(isset($modelLn[$k])) $modelLn[$k]=$v;
				}
				$sql=false;
	      $sqlLn="REPLACE INTO city_name SET cit_key=:cit_key, cit_name=:cit_name, cit_ln=:ln";
				$valsLn[':cit_key']=$data['cit_id'];
			}
		}

		//Добавление
	  if( empty($data['cit_id']) ){
	    $mode='insert';
	    
	    if( empty($data['cit_name']) )
				return $this->error('ctr_name expected');
				//throw_error('ctr_name expected',500);

			$req=$data;
			$req['addr']=$data['cit_name'];
			$req['lang']='en';

			//Проверка в гугле
			if( !$googleInfo=$this->getMaps()->geocode( $req ) )
			  return $this->error($this->getMaps()->getError());
				//throw_error($this->getMaps()->getError(),500);

			if(empty( $googleInfo['city'] ))
				return $this->error('City name error');
				//throw_error('City name error',500);

			$data['cit_sysname']=$googleInfo['city'];
			//$data['cit_id']='ct'.md5($googleInfo['city']);
			$data['cit_id']=$this->getCitId($googleInfo['city']);

      //Ищу в базе существующее
      $tst=$this->makeGet('/city/'.$data['cit_id']);
			if(!empty($tst)){
			  if(!empty($tst['cit_name']))
				  return array('result'=>'fail','info'=>'City alredy exists','model'=>$tst);
        $sql=false;
			}else{
			  $sql="INSERT INTO city SET {fields} ";
			}

			//Сохраняю Регион
			if( !$tst=$this->postRegion( array_merge($googleInfo,array('reg_name'=>$googleInfo['region'])) )  )
				return $this->error('Error create region "'.$googleInfo['region'].'"');
				//throw_error('Error create region "'.$googleInfo['region'].'"',400);
			if( empty($tst['model']) )
				return $this->error('Error create region "'.$googleInfo['region'].'"');
				//throw_error('Error create country "'.$googleInfo['region'].'"',400);
			$region=$tst['model'];
			$country=array('ctr_id'=>$region['ctr_id']);
			

	    //Получаю по текщему языку
	    if($this->api->lang=='en' || !$translateted=getTranslate()->translate( $googleInfo['city'],'en',$this->api->lang )){
			  $translateted=$googleInfo['city'];
			}

			$data['cit_key_ctr']=$country['ctr_id'];
			$data['cit_key_reg']=$region['reg_id'];
			$data['cit_name']=$translateted;
	    $data['cit_geometry']=$googleInfo['geometry'];

	    if( !$this->getValid()->city($data) )
				return $this->error('region model validation error');
				//throw_error('region model validation error',400);
	    
	    $sqlLn="REPLACE INTO city_name SET {fields} ";
		}

	  $data['cit_key']=$data['cit_id'];

		if($sql){
		  foreach($model as $k=>$v){
				$fields[]=$k.'=:'.$k;
		    $vals[':'.$k]=(isset($data[$k]))?$data[$k]:$v;
			}

			$sql=str_replace('{fields}',implode(',', $fields),$sql);
		  $this->setData($sql, $vals);
		}

	  foreach($modelLn as $k=>$v){
			$fieldsLn[]=$k.'=:'.$k;
	    $valsLn[':'.$k]=(isset($data[$k]))?$data[$k]:$v;
		}

		$sqlLn=str_replace('{fields}',implode(',', $fieldsLn),$sqlLn);
		$this->setData($sqlLn, $valsLn);

	  //$model=array_merge($model, $modelLn, $data);
	  $model=$this->makeGet('/city/'.$data['cit_id']);

    $text=$model['ctr_sysname'].' '.$model['ctr_name'].' '.
					$model['reg_sysname'].' '.$model['reg_name'].' '.
					$model['cit_sysname'].' '.$model['cit_name'];
//echo 'CITY<pre class="debug">'.print_r ( $model ,true).'</pre>';
    $this->storeSearch($model['cit_id'], $text);

	  return array('result'=>'success','info'=>'','model'=>$model);
	}
	
	public function postUrban($data=array()){
	  if(empty($data)) $data=$this->api->env['_POST'];;
	  
		$fields=array();$vals=array();$fieldsLn=array();$valsLn=array();
    $model=array(
      'ua_id'=>'',
			'ua_sysname'=>'',
			'ua_key_ctr'=>'',
			'ua_key_reg'=>'',
			'ua_key_cit'=>'',
		);
		$modelLn=array(
			'ua_key'=>'',
			'ua_name'=>'',
			'ua_ln'=>$this->api->lang,
		);

		//Редактирование
		if( !empty($data['ua_id']) ){
		  $mode='update';
	    $modelBase=$this->makeGet('/urban/'. $data['ua_id'] );

			//Если нет такого решиона
	    if(	empty($modelBase)	) unset($data['ua_id'],$modelBase);
	    else{
	      $modelBase['ua_key']=$modelBase['ua_id'];
	      foreach($modelBase as $k=>$v){
		      if(isset($modelLn[$k])) $modelLn[$k]=$v;
				}
				$sql=false;
	      $sqlLn="REPLACE INTO urbanarea_name SET ua_key=:ua_key, ua_name=:ua_name, ua_ln=:ln";
				$valsLn[':ua_key']=$data['ua_key'];
			}
		}

		//Добавление
	  if( empty($data['ua_id']) ){
	    $mode='insert';
	    
	    if( empty($data['ua_name']) )
				return $this->error('ua_name expected');
				//throw_error('ua_name expected',500);

      $req=$data;
      $req['addr']=$data['ua_name'];
			$req['lang']='en';

			if((!empty($data['ctr_id']))) 	$req['country']=$data['ctr_id'];
			if((!empty($data['reg_name']))) $req['region']=$data['reg_name'];
			if((!empty($data['cit_name']))) $req['city']=$data['cit_name'];

			//Проверка в гугле
			if( !$googleInfo=$this->getMaps()->geocode( $req ) )
				return $this->error($this->getMaps()->getError());

			if(empty( $googleInfo['urbanarea'] ))
				return $this->error('Urbanarea name error');

			$data['ua_sysname']=$googleInfo['urbanarea'];
			//$data['ua_id']='ub'.md5($googleInfo['urbanarea']);
			$data['ua_id']=$this->getUaId($googleInfo['urbanarea']);

      //Ищу в базе существующее
      $tst=$this->makeGet('/urbanarea/'.$data['ua_id']);

			if(!empty($tst)){
			  if(!empty($tst['ua_name']))
			  	return array('result'=>'fail','info'=>'City alredy exists','model'=>$tst);
			  $sql=false;
			}else{
			  $sql="INSERT INTO urbanarea SET {fields} ";
			}

      //Сохраняю Город
			if( !$tst=$this->postCity(array('cit_name'=>$googleInfo['city'],'ctr_name'=>$googleInfo['country'],'reg_name'=>$googleInfo['region']))  )
				return $this->error('Error create region "'.$googleInfo['region'].'"');
				//throw_error('Error create city "'.$googleInfo['city'].'"',400);
			if( empty($tst['model']) )
				return $this->error('Error create region "'.$googleInfo['region'].'"');
				//throw_error('Error create city "'.$googleInfo['city'].'"',400);
			$city=$tst['model'];
			$country=array('ctr_id'=>$city['ctr_id']);
			$region=array('reg_id'=>$city['reg_id']);

	    //Получаю по текщему языку
	    if($this->api->lang=='en' || !$translateted=getTranslate()->translate( $googleInfo['urbanarea'],'en',$this->api->lang )){
			  $translateted=$googleInfo['urbanarea'];
			}

			$data['ua_key_ctr']=$country['ctr_id'];
			$data['ua_key_reg']=$region['reg_id'];
			$data['ua_key_cit']=$city['cit_id'];
			$data['ua_name']=$translateted;
	    $data['ua_geometry']=$googleInfo['geometry'];

	    if( !$this->getValid()->urbanarea($data) )
				return $this->error('region model validation error');
				//throw_error('urbanarea model validation error',400);

	    
	    $sqlLn="REPLACE INTO urbanarea_name SET {fields} ";
		}

	  $data['ua_key']=$data['ua_id'];

	  foreach($modelLn as $k=>$v){
			$fieldsLn[]=$k.'=:'.$k;
	    $valsLn[':'.$k]=(isset($data[$k]))?$data[$k]:$v;
		}

		if($sql){
		  foreach($model as $k=>$v){
				$fields[]=$k.'=:'.$k;
		    $vals[':'.$k]=(isset($data[$k]))?$data[$k]:$v;
			}

			$sql=str_replace('{fields}',implode(',', $fields),$sql);
		  $this->setData($sql, $vals);
		}

		$sqlLn=str_replace('{fields}',implode(',', $fieldsLn),$sqlLn);
		$this->setData($sqlLn, $valsLn);

	  //$model=array_merge($model, $modelLn, $data);
	  $model=$this->makeGet('/urban/'.$data['ua_id']);

    $text=$model['ua_sysname'].' '.$model['ua_name'];
//echo 'URBAN<pre class="debug">'.print_r ( $model ,true).'</pre>';
    $this->storeSearch($model['ua_id'], $text);

	  return array('result'=>'success','info'=>'','model'=>$model);
	}
	
	public function postAddr($data=array()){
	  if(empty($data)) $data=$this->api->env['_POST'];;
	  
		$fields=array();$vals=array();$fieldsLn=array();$valsLn=array();
    $model=array(
      'addr_id'=>'',
			'addr_sysname'=>'',
			'addr_lat'=>'',
			'addr_lng'=>'',
			'addr_key_ctr'=>'',
			'addr_key_reg'=>'',
			'addr_key_cit'=>'',
			'addr_key_ua'=>'',
		);
		$modelLn=array(
			'addr_key'=>'',
			'addr_name'=>'',
			'addr_ln'=>$this->api->lang,
		);

		//Редактирование
		if( !empty($data['addr_id']) ){
		  $mode='update';
	    $modelBase=$this->makeGet( '/addr/'. $data['addr_id'] );

			//Если нет такого решиона
	    if(	empty($modelBase)	) unset($data['addr_id'],$modelBase);
	    else{
	      $modelBase['addr_key']=$modelBase['addr_id'];
	      foreach($modelBase as $k=>$v){
		      if(isset($modelLn[$k])) $modelLn[$k]=$v;
				}
				$sql=false;
	      $sqlLn="REPLACE INTO addr_name SET addr_key=:addr_key, addr_name=:addr_name, addr_ln=:ln";
				$valsLn[':addr_key']=$data['addr_key'];
			}
		}

		//Добавление
	  if( empty($data['addr_id']) ){
	    $mode='insert';
	    if( empty($data['addr_name']) )
				return $this->error('addr_name expected');
				//throw_error('addr_name expected',500);

			//GEOCODING, если чего-то важного нет
			if(
				empty($data['geometry']) || empty($data['lat']) || empty($data['lng']) ||
				empty($data['countryIso']) || empty($data['region']) || empty($data['city']) ||
				empty($data['street']) || empty($data['number'])
			){
				$req=$data;
	      $req['addr']=$data['addr_name'];
				$req['lang']=='en';
				if((!empty($data['ctr_id']))) $req['country']=$data['ctr_id'];
				if((!empty($data['reg_name']))) $req['region']=$data['reg_name'];
	   		if((!empty($data['cit_name']))) $req['city']=$data['cit_name'];
	   		if((!empty($data['ua_name']))) $req['urban']=$data['ua_name'];

				if( !$googleInfo=$this->getMaps()->geocode( $req ) )
					//throw_error($this->getMaps()->getError(),500);
					return $this->error($this->getMaps()->getError());

				if( empty( $googleInfo['number'] ) )	//throw_error('Missing address number',500);
				  return $this->error('Missing address number');
				if( empty( $googleInfo['street'] ) )	//throw_error('Missing street name',500);
				  return $this->error('Missing street number');
			}else
			  $googleInfo=$data;
			

			$data['addr_sysname']=$googleInfo['formatedAddr'];
			$data['addr_id']='ad'.md5($googleInfo['formatedAddr']);

      //Ищу в базе существующее
      $tst=$this->makeGet('/addr/'.$data['addr_id']);

			if(!empty($tst)){
			  if(!empty($tst['addr_name']))
			  	return array('result'=>'fail','info'=>'Address alredy exists','model'=>$tst);
			  $sql=false;
			}else{
			  $sql="INSERT INTO addr SET {fields} ";
			}

			if(!empty($googleInfo['urbanarea'])){
	      //Сохраняю Район
	      $data['ua_name']=$googleInfo['urbanarea'];
	      
				if( !$tst=$this->postUrban( array_merge($googleInfo,$data) )  )
					//throw_error('Error create urbanarea "'.$googleInfo['urbanarea'].'"',400);
					return $this->error('Error create urbanarea "'.$googleInfo['urbanarea'].'"');
				if( empty($tst['model']) )
					//throw_error('Error create urbanarea "'.$googleInfo['urbanarea'].'"',400);
					return $this->error('Error create urbanarea "'.$googleInfo['urbanarea'].'"');

				$urban=$this->makeGet('/urbanarea/'.$tst['model']['ua_id']);
				$country=array('ctr_id'=>$urban['ctr_id']);
				$region=array('reg_id'=>$urban['reg_id']);
				$city=array('cit_id'=>$urban['cit_id']);
			}else{
	      //Сохраняю Город
				if( !$tst=$this->postCity($data)  )
					//throw_error('Error create city "'.$googleInfo['city'].'"',400);
					return $this->error('Error create city "'.$googleInfo['city'].'"');
				if( empty($tst['model']) )
					//throw_error('Error create city "'.$googleInfo['city'].'"',400);
					return $this->error('Error create city "'.$googleInfo['city'].'"');
					
				$city=$this->makeGet('/city/'.$tst['model']['cit_id']);
				$country=array('ctr_id'=>$city['ctr_id']);
				$region=array('reg_id'=>$city['reg_id']);
				$urban=array('ua_id'=>false);
			}

	    //Получаю по текщему языку
	    if($this->api->lang=='en' || !$translateted=getTranslate()->translate( $googleInfo['formatedAddr'],'en',$this->api->lang )){
			  $translateted=$googleInfo['formatedAddr'];
			}

			$data['addr_key_ctr']=$country['ctr_id'];
			$data['addr_key_reg']=$region['reg_id'];
			$data['addr_key_cit']=$city['cit_id'];
			$data['addr_name']=$translateted;
			$data['addr_lat']=$googleInfo['lat'];
			$data['addr_lng']=$googleInfo['lng'];

			if(!empty($urban))	$data['addr_key_ua']=$urban['ua_id'];

	    if( !$this->getValid()->addr($data) )
				//throw_error('address model validation error',400);
				return $this->error('address model validation: '.implode(',',$this->getValid()->getErrors()));

	    
	    $sqlLn="REPLACE INTO addr_name SET {fields} ";

		  foreach($model as $k=>$v){
				$fields[]=$k.'=:'.$k;
		    $vals[':'.$k]=(isset($data[$k]))?$data[$k]:$v;
			}
		}

	  $data['addr_key']=$data['addr_id'];

	  foreach($modelLn as $k=>$v){
			$fieldsLn[]=$k.'=:'.$k;
	    $valsLn[':'.$k]=(isset($data[$k]))?$data[$k]:$v;
		}

		if($sql){
			$sql=str_replace('{fields}',implode(',', $fields),$sql);
		  $this->setData($sql, $vals);
		}

		$sqlLn=str_replace('{fields}',implode(',', $fieldsLn),$sqlLn);
		$this->setData($sqlLn, $valsLn);

	  //$model=array_merge($model, $modelLn, $data);
	  $model=$this->makeGet('/addr/'.$data['addr_id']);

    $text=$model['ctr_sysname'].' '.$model['ctr_name'].' '.
					$model['reg_sysname'].' '.$model['reg_name'].' '.
					$model['cit_sysname'].' '.$model['cit_name'].' '.
					$model['ua_sysname'].' '.$model['ua_name'].' '.
					$model['addr_sysname'].' '.$model['addr_name'];
//echo 'ADDRPOINT<pre class="debug">'.print_r ( $model ,true).'</pre>';
    $this->storeSearch($model['addr_id'], $text);

	  return array('result'=>'success','info'=>'','model'=>$model);
	}

	public function postPoint($data=array()){
		if(empty($data)) $data=$this->api->env['_POST'];;

		$fields=array();$vals=array();$fieldsLn=array();$valsLn=array();
    $model=array(
      'p_id'=>'',
			'p_sysname'=>'',
			'p_lat'=>'',
			'p_lng'=>'',
			'p_key_ctr'=>'',
			'p_key_reg'=>'',
			'p_key_cit'=>'',
			'p_key_ua'=>'',
			'p_key_addr'=>'',
			'p_key_net'=>'',
			'p_data_provider'=>'',
			'p_provider_info'=>'',
			'p_managed'=>'',
		);
		$modelLn=array(
			'p_key'=>'',
			'p_name'=>'',
			'p_ln'=>$this->api->lang,
		);

		//Редактирование
		if( !empty($data['p_id']) ){
		  $mode='update';
	    $modelBase=$this->makeGet( '/point/'. $data['p_id'] );

			//Если нет такого 
	    if(	empty($modelBase)	) unset($data['p_id'],$modelBase);
	    else{
	      $modelBase['p_key']=$modelBase['p_id'];
	      foreach($modelBase as $k=>$v){
		      if(isset($modelLn[$k])) $modelLn[$k]=$v;
				}
				$sql=false;
	      $sqlLn="REPLACE INTO point_name SET p_key=:p_key, p_name=:p_name, p_ln=:ln";
				$valsLn[':p_key']=$data['p_key'];
			}
		}

		//Добавление
	  if( empty($data['p_id']) ){
	    $mode='insert';

	    if( empty($data['p_addr']) ) //throw_error('p_addr expected',500);
	      return $this->error('p_addr expected');
	    if( empty($data['p_name']) ) //throw_error('p_name expected',500);
	    	return $this->error('p_name expected');
	    if( !isset($data['p_isNetwork']) ) //throw_error('p_isNetwork expected',500);
	      return $this->error('p_isNetwork expected');
	    if( !is_int($data['p_isNetwork']) && !is_bool($data['p_isNetwork'])) //throw_error('expected bool or int p_isNetwork',500);
	      return $this->error('expected bool or int p_isNetwork');

			//Пытаюсь геокодить место
			$req=$data;
      //$req=array('addr'=>$data['p_addr'], 'lang'=>'en');
      
      $data['p_addr']=strtr($data['p_addr'], array('г.'=>'','ул.'=>'','просп.'=>'',));
   		$req['addr']=$data['p_addr'];
			$req['lang']='en';
			if((!empty($data['ctr_id']))) $req['country']=$data['ctr_id'];
			if((!empty($data['reg_name']))) $req['region']=$data['reg_name'];
   		if((!empty($data['cit_name']))) $req['city']=$data['cit_name'];
   		if((!empty($data['ua_name']))) $req['urban']=$data['ua_name'];
   		
			if( !$googleInfo=$this->getMaps()->geocode( $req ) )
				//throw_error('Address search error: '.$this->getMaps()->getError(),500);
				return $this->error('Address search error: '.$this->getMaps()->getError());

			$conv=array(
			  'countryIso'=>'ctr_id',
			  'country'=>'ctr_name',
			  'region'=>'reg_name',
			  'city'=>'cit_name',
			  'urbanarea'=>'ua_name',
			  'street'=>'p_street',
			  'number'=>'p_number',
			  'lat'=>'p_lat',
			  'lng'=>'p_lng',
			);
			$convi=array_flip($conv);

			foreach($googleInfo as $k=>$v){
			  //if( empty($data[ $conv[$k] ]) && !empty($googleInfo[ $k ]) )
			  if( empty($conv[$k] ) ) continue;
			  if( empty($data[ $conv[$k] ]) && !empty($googleInfo[ $k ]) )
			    $data[ $conv[$k] ]=$googleInfo[ $k ];
			}

      $radius=100;
			if(	empty( $googleInfo['number'] ) || empty( $googleInfo['street'] )	) {
        $radius=false;
			}
//echo '<pre class="debug">'.print_r ( $data ,true).'</pre>';
//echo '<pre>',print_r( $googleInfo, true),'</pre>'; exit();

			//Пробую найти место в Foursquare и googlePlaces
			$req=array(
			  'lat'=>$googleInfo['lat'],
				'lng'=>$googleInfo['lng'],
				'query'=>$data['p_name'],
				'fullQuery'=>$data['p_addr'].' '.$data['p_name'],
				'radius'=>$radius,
				'lang'=>$this->api->lang,
			);
//echo 'Find req: <pre class="debug">'.print_r ( $req ,true).'</pre>';
      $data['p_managed']=1;
      
			if(!$placeInfo=$this->getFoursquare()->find( $req )) //Поиск в форсквере
      if(!$placeInfo=$this->getMaps()->find( $req ))       //Поиск в GooglePlaces
			//if(!$placeInfo=$this->getMaps()->find( $req ,'Yandex')) //Поиск в Yandex картах
			{
        if(	empty( $googleInfo['number'] ) || empty( $googleInfo['street'] )	)
          return $this->error('Refine address');
      	$data['p_managed']=0;
			}
//echo '<pre>',print_r( $placeInfo, true),'</pre>';exit();
			if(!empty($placeInfo['dataProvider'])){
				$data['p_data_provider']=$placeInfo['dataProvider'];
				$data['p_provider_info']=json_encode($placeInfo['wideInfo']);
			}else $data['p_data_provider']='XX';
			//Строю p_id
			$data['p_id']=$this->getPntId($placeInfo['name'],$googleInfo['lat'],$googleInfo['lng']);
			
			if(empty($data['p_number']) && !empty($placeInfo['number'])){
			  $data['p_number']=$placeInfo['number'];
			}

      //Ищу в базе существующее
      $tst=$this->makeGet('/point/'.$data['p_id']);

			if(!empty($tst)){
			  //Таккая точка есть
				if(!empty($tst['p_name']))
			  	return array('result'=>'fail','info'=>'point alredy exists','model'=>$tst);
			  $sql=false;
			}else{
			  //Такой точки нет
			  $sql="INSERT INTO point SET {fields} ";
			  //Если нет полного адреса, но есть latLng
				if(
					(empty($data['p_street']) || empty($data['p_number'])) &&
					!empty($data['p_lat']) && !empty($data['p_lng'])
				){
					$tmp=$this->getMaps()->geocode( array(
						'lat'=>$data['p_lat'],
						'lng'=>$data['p_lng'],
						'filter'=>array(
							0=>'street_number,test'
						)
					));

					//$placeInfo=array_merge($placeInfo, $tmp);
					if(!empty($tmp['street'])) $data['p_street']=$tmp['street'];
					if(!empty($tmp['number'])) $data['p_number']=$tmp['number'];
					unset($tmp);
				}
			}
//echo '<pre>',print_r( $data, true),'</pre>'; exit();

      if($data['p_isNetwork'] || ( !empty($tst['net_id']) ) ){
        if( !empty($tst['net_id']) ){
          $network=$this->makeGet('/network/'.$tst['net_id']);
				}else{
				  //Пытаюсь найти сеть
				  $tn=$this->makeGet('/network/'.$data['p_name']);
				  
				  if(empty($tn)){
						//Сохраняю сеть
						if( !$tst=$this->postNet(array('net_name'=>$data['p_name']))  )
							return $this->error('Error create network "'.$placeInfo['name'].'"');
						if( empty($tst['model']) )
							return $this->error('Empty created network model "'.$placeInfo['name'].'"');
						$network=$tst['model'];
					}else
					  $network=$tn;
          unset($tn);
				}
			}else{
				$network=$this->makeGet('/network/'.$data['p_name']);
			}
//echo '<pre>',print_r( $network, true),'</pre>';exit();
			unset($tst);
			
			
			if(empty($network)){
			  $network=$this->makeGet('/network/nte4343eadb9608afee19449cd33638680'); //Самостоятельная торговая точка
			  //Если вдруг нету дефолтной ТТ - создать
			  if(empty($network)){
			    $t=$this->postNet(array('net_name'=>'Самостоятельная торговая точка'));
			    if(empty($t['model']))	return $this->error('Error create network "Самостоятельная торговая точка"');
			    $network=$t['model'];
				}
			}else{
			  $data['p_name']=$network['net_name'];
			}
			$data=array_merge($network,$data);

			if(!empty($data['ua_name'])){
				if( !$tst=$this->postUrban($data,true))
					return $this->error('Error create urbanarea "'.$data['ua_name'].'" '.$this->getError());
				if( empty($tst['model']) )
					return $this->error('Error create urbanarea "'.$data['ua_name'].'"');
				$storedData=$tst['model'];
			}elseif(!empty($data['cit_name'])){
			  if( !$tst=$this->postCity($data,true))
					return $this->error('Error create city "'.$data['cit_name'].'" '.$this->getError());
				if( empty($tst['model']) )
					return $this->error('Error create city "'.$data['cit_name'].'"');
				$storedData=$tst['model'];
			}else
			  return $this->error('not enougth data to store point');
			  
      //foreach($storedData as $k=>$v)if( empty($data[ $k ]) && !empty($storedData[$k]) ) $data[$k]=$storedData[$k];
			$data=array_merge($storedData,$data);

/*
			//Сохраняю адрес
			$addrStr=$googleInfo['street'].' '.$googleInfo['number'].' '.$googleInfo['city'].' '.$googleInfo['country'];
			if( !$tst=$this->postAddr(
				array_merge(
					$googleInfo,
					array(
						'addr_name'=>$addrStr
					)
				),
				true
			))
				//throw_error('Error create address "'.$googleInfo['formatedAddr'].'"',400);
				return $this->error('Error create address "'.$addrStr.'" '.$this->getError());
			if( empty($tst['model']) )
    		//throw_error('Error create address "'.$googleInfo['formatedAddr'].'"',400);
				return $this->error('Error create address "'.$addrStr.'"');
			$address=$tst['model'];
*/

	    //Получаю по текщему языку
	    if($this->api->lang!='en'){
			  //$translateted=getTranslate()->translate( $googleInfo['formatedAddr'],'en',$this->api->lang )
        //ksort($data);
        $tray=array(
          'ctr_name'=>$data['ctr_name'],
          'reg_name'=>$data['reg_name'],
					'cit_name'=>$data['cit_name'],
					'ua_name'=>$data['ua_name'],
					'p_street'=>$data['p_street']
				);
        $t=implode(" | ", $tray);
        $translateted=getTranslate()->translate( $t,'en',$this->api->lang );
        $t=explode(" | ", $translateted);
        $i=0; foreach($tray as $k=>$v){
          $data[$k] = $t[$i];
          $i++;
				}
				//echo '<pre>',print_r( $data, true),'</pre>';exit();
			}

			$data['p_key_ctr']=$data['ctr_id'];
			$data['p_key_reg']=$data['reg_id'];
			$data['p_key_cit']=$data['cit_id'];
			$data['p_key_ua']=$data['ua_id'];
			$data['p_key_net']=$data['net_id'];
			$addr=$data['p_street'].' '.$data['p_number'].' '.$data['cit_name'].' '.$data['reg_name'].' '.$data['ctr_id'];
			$data['p_sysname']=translit($data['p_name'].' '.$addr);
			$data['p_name']=$data['p_name'].' '.$addr;
			if(!empty($data['ua_id'])) $data['p_key_ua']=$data['ua_id'];
	    if( !$this->getValid()->point($data) )
				return $this->error('point model validation error');
	    
	    $sqlLn="REPLACE INTO point_name SET {fields} ";
		}

	  $data['p_key']=$data['p_id'];

		if($sql){
		  foreach($model as $k=>$v){
				$fields[]=$k.'=:'.$k;
		    $vals[':'.$k]=(isset($data[$k]))?$data[$k]:$v;
			}
			$sql=str_replace('{fields}',implode(',', $fields),$sql);
		  $this->setData($sql, $vals);
		}

	  foreach($modelLn as $k=>$v){
			$fieldsLn[]=$k.'=:'.$k;
	    $valsLn[':'.$k]=(isset($data[$k]))?$data[$k]:$v;
		}

		$sqlLn=str_replace('{fields}',implode(',', $fieldsLn),$sqlLn);
		$this->setData($sqlLn, $valsLn);

	  
	  $model=$this->makeGet('/point/'.$data['p_id']);

    $text=$model['ctr_sysname'].' '.$model['ctr_name'].' '.
					$model['reg_sysname'].' '.$model['reg_name'].' '.
					$model['cit_sysname'].' '.$model['cit_name'].' '.
					$model['ua_sysname'].' '.$model['ua_name'].' '.
					$model['p_sysname'].' '.$model['p_name'];
    $this->storeSearch($model['p_id'], $text);
	  return array('result'=>'success','info'=>'','model'=>$model);
	}
	
	public function postPointManual($data=array()){
	  if(empty($data)) $data=$this->api->env['_POST'];;
	  
		$fields=array();$vals=array();$fieldsLn=array();$valsLn=array();
    $model=array(
      'p_id'=>'',
			'p_sysname'=>'',
			'p_lat'=>'',
			'p_lng'=>'',
			'p_key_ctr'=>'',
			'p_key_reg'=>'',
			'p_key_cit'=>'',
			'p_key_ua'=>'',
			'p_key_addr'=>'',
			'p_key_net'=>'',
			'p_data_provider'=>'',
			'p_provider_info'=>'',
			'p_managed'=>'',
		);
		$modelLn=array(
			'p_key'=>'',
			'p_name'=>'',
			'p_ln'=>$this->api->lang,
		);

		//Редактирование
		if( !empty($data['p_id']) ){
		  $mode='update';
	    $modelBase=$this->makeGet( '/point/'. $data['p_id'] );
	    if(	empty($modelBase)	) unset($data['p_id'],$modelBase);
	    else{
	      $modelBase['p_key']=$modelBase['p_id'];
	      foreach($modelBase as $k=>$v){
		      if(isset($modelLn[$k])) $modelLn[$k]=$v;
				}
				$sql="REPLACE INTO point SET
							p_id=:p_id,p_key_addr=:p_key_addr,p_key_net=:net_id, p_key_ctr=:ctr_id, p_key_reg=:reg_id, p_key_cit=:cit_id,
							p_key_ua=:ua_id,p_lat=:p_lat,p_lng=:p_lng, p_sysname=:p_sysname,
							p_data_provider=:p_data_provider, p_provider_info=:p_provider_info,p_managed=:p_managed";
				$vals[':p_id']=$data['p_id'];
	      $sqlLn="REPLACE INTO point_name SET p_key=:p_key, p_name=:p_name, p_ln=:ln";
				$valsLn[':p_key']=$data['p_key'];
			}
		}

		//Добавление
	  if( empty($data['p_id']) ){
	    $mode='insert';
      //$ids=array('countryID','regionID','cityID','urbanID','networkID');
      //$strs=array('lat','lng','country','region','city','urban','street','number','network');

      if(!empty($data['ua_id'])) 			$dbdata=$this->makeGet('/urbanarea/'.$data['ua_id']);
      elseif(!empty($data['cit_id'])) $dbdata=$this->makeGet('/city/'.$data['cit_id']);
      elseif(!empty($data['reg_id'])) $dbdata=$this->makeGet('/region/'.$data['reg_id']);
      elseif(!empty($data['ctr_id'])) $dbdata=$this->makeGet('/country/'.$data['ctr_id']);
      if(!empty($data['net_id'])) {
				if($net=$this->makeGet('/network/'.$data['net_id']))
					$dbdata=array_merge($dbdata,$net);
					$data['p_isNetwork']=1;
			}

			if(
				( empty($data['p_street']) || empty($data['p_number']) ) &&
				( empty($data['p_lat']) || empty($data['p_lng']) )
			)   return $this->error('not enough params for point');
			
			//Пытаюсь последовательно геокодить от большего к меньшему
			$conv=array(
			  'countryIso'=>'ctr_id',
			  'country'=>'ctr_name',
			  'region'=>'reg_name',
			  'city'=>'cit_name',
			  'urbanarea'=>'ua_name',
			  'street'=>'p_street',
			  'number'=>'p_number',
			  'lat'=>'p_lat',
			  'lng'=>'p_lng',
			);
			$convi=array_flip($conv);

			$geocodeStr='';
			$keys=array('ctr_name','reg_name','cit_name','ua_name',);
						
			//foreach($keys as $k=>$v){
			for($i=0,$cnt=count($keys);$i<$cnt; $i++){
			  if( !empty($data[ $keys[$i] ]) ) $geocodeStr.=' '.$data[$keys[$i]];
				elseif( !empty($dbdata[$keys[$i]]) ) $geocodeStr.=' '.$dbdata[$keys[$i]];
			}
			if(!empty($data['p_street'])){
			  $geocodeStr.=' '.$data['p_street'];
			  if(!empty($data['p_number'])) $geocodeStr.=' '.$data['p_number'];
			}
			if(!empty($dbdata['net_name'])) $data['p_name']=$dbdata['net_name'];

			//Пробую найти место в Foursquare, googlePlaces, Yandex
			$req=array(
				'query'=>$data['p_name'],
				'fullQuery'=>$geocodeStr,
				'radius'=>50,
				'intent'=>'browse',
				'lang'=>$this->api->lang,
			);
			if(!empty($data['p_lat']))	$req['lat']=$data['p_lat'];
   		if(!empty($data['p_lng']))	$req['lng']=$data['p_lng'];

//echo 'Find req: <pre class="debug">'.print_r ( $req ,true).'</pre>'; exit();
      $data['p_managed']=1;

			if(!$placeInfo=$this->getFoursquare()->find( $req )) //Поиск в форсквере
      if(!$placeInfo=$this->getMaps()->find( $req ))       //Поиск в GooglePlaces
			//if(!$placeInfo=$this->getMaps()->find( $req ,'Yandex')) //Поиск в Yandex картах
        {
					$placeInfo=false;
					$data['p_managed']=0;
					if( empty($data['ctr_id']) || empty($data['reg_name']) || empty($data['cit_name']) || empty($data['p_street']) || empty($data['p_number']) ){
						$req=array(
						  'lat'=>$data['p_lat'],
						  'lng'=>$data['p_lng'],
						);
						$req['lang']=$this->api->lang;
						//$req['lang']='en';
						if((!empty($data['ctr_id'])))	$req['country']=$data['ctr_id'];
						elseif((!empty($data['ctr_name'])))	$req['country']=$data['ctr_name'];
						if((!empty($data['reg_name'])))			$req['region']=$data['reg_name'];
			   		if((!empty($data['cit_name'])))				$req['city']=$data['cit_name'];

						if( !$googleInfo=$this->getMaps()->geocode( $req ) )
							return $this->error('Address search error: '.$this->getMaps()->getError());
						
						foreach($data as $k=>$v)
						  if( empty($data[$k]) && !empty($googleInfo[ $convi[$k] ]) )
						    $data[$k]=$googleInfo[ $convi[$k] ];
					}
        }
//echo '$req<pre class="debug">'.print_r ( $req ,true).'</pre>';
//echo '$placeInfo<pre class="debug">'.print_r ( $placeInfo ,true).'</pre>';exit();
			if(!empty($placeInfo['dataProvider'])){
				$data['p_data_provider']=$placeInfo['dataProvider'];
				$data['p_provider_info']=json_encode($placeInfo['wideInfo']);
				//$t=explode('.', $placeInfo['lat']); $data['p_lat']=$t[0].'.'.substr($t[1], 0, 4);
				//$t=explode('.', $placeInfo['lng']); $data['p_lng']=$t[0].'.'.substr($t[1], 0, 4);
				foreach($data as $k=>$v)
					if(empty($data[$k]) && !empty($placeInfo[ $convi[$k] ])) $data[$k]=$placeInfo[ $convi[$k] ];
			}else $data['p_data_provider']='XX';
			
			//Строю p_id
			$data['p_id']=$this->getPntId($data['name'],$data['lat'],$data['lng'] );

      //Ищу в базе существующее
      $tst=$this->makeGet('/point/'.$data['p_id']);
			if(!empty($tst)){
			  //Таккая точка есть
				if(!empty($tst['p_name']))
			  	return array('result'=>'fail','info'=>'point alredy exists','model'=>$tst);
			  $sql=false;
			}else{
			  //Такой точки нет
			  $sql="INSERT INTO point SET {fields} ";
			}

      if($data['p_isNetwork'] && empty($data['net_id']) ){
				//Пытаюсь найти сеть
				$tn=$this->makeGet('/network/'.$data['p_name']);
				if(empty($tn)){
					//Сохраняю сеть
					if( !$tst=$this->postNet(array('net_name'=>$data['p_name']))  )
						return $this->error('Error create network "'.$data['p_name'].'"');
					if( empty($tst['model']) )
						return $this->error('Error create network "'.$data['p_name'].'"');
					$network=$tst['model'];
				}else
					$network=$tn;
        unset($tn);
			}else{
//echo '/network/'.$data['p_name'];
				$network=$this->makeGet('/network/'. translit($data['p_name']) );
			}

			if(empty($network)){
			  $network=$this->makeGet('/network/nte4343eadb9608afee19449cd33638680'); //Самостоятельная торговая точка
			  //Если вдруг нету дефолтной ТТ - создать
			  if(empty($network)){
			    $t=$this->postNet(array('net_name'=>'Самостоятельная торговая точка'));
			    if(empty($t['model']))	return $this->error('Error create network "Самостоятельная торговая точка"');
			    $network=$t['model'];
				}
			}
			$data['net_id']=$network['net_id'];

			if(!empty($data['ua_name'])){
				if( !$tst=$this->postUrban($data,true))
					return $this->error('Error create urbanarea "'.$data['ua_name'].'" '.$this->getError());
				if( empty($tst['model']) )
					return $this->error('Error create urbanarea "'.$data['ua_name'].'"');
				$storedData=$tst['model'];
			}elseif(!empty($data['cit_name'])){
			  if( !$tst=$this->postCity($data,true))
					return $this->error('Error create city "'.$data['cit_name'].'" '.$this->getError());
				if( empty($tst['model']) )
					return $this->error('Error create city "'.$data['cit_name'].'"');
				$storedData=$tst['model'];
			}else
			  return $this->error('not enougth data to store point');
			  
      foreach($data as $k=>$v)
        if( empty($data[$k]) && !empty($storedData[$k]) ) $data[$k]=$storedData[$k];

	    if( !$this->getValid()->point($data) )
				//throw_error('point model validation error',400);
				return $this->error('point model validation error');

	    $sqlLn="REPLACE INTO point_name SET {fields} ";
		}

	  $data['p_key']=$data['p_id'];
	  $data['p_sysname'] = translit($data['p_name'].' '.$data['p_street'].' '.$data['p_number'].' '.$data['cit_name'].' '.$data['reg_name'].' '.$data['ctr_id'] );
	  $data['p_key_ctr']=$data['ctr_id'];
	  $data['p_key_reg']=$data['reg_id'];
	  $data['p_key_cit']=$data['cit_id'];
	  $data['p_key_ua']=$data['ua_id'];
	  $data['p_key_addr']=false;
		$data['p_key_net']=$data['net_id'];
		$data['p_name'].=$data['net_id'].' '.$data['p_street'].' '.$data['p_number'].' '.$data['cit_name'].' '.$data['reg_name'].' '.$data['ctr_id'];
//echo '<pre class="debug">'.print_r ( $data ,true).'</pre>';exit();

		if($sql){
		  foreach($model as $k=>$v){
				$fields[]=$k.'=:'.$k;
		    $vals[':'.$k]=(isset($data[$k]))?$data[$k]:$v;
			}

			$sql=str_replace('{fields}',implode(',', $fields),$sql);

			//echo '<pre class="debug">'.print_r ( $data ,true).'</pre>';
			//echo $sql.'<pre class="debug">'.print_r ( $vals ,true).'</pre>'; exit();
		  $this->setData($sql, $vals);
		}

	  foreach($modelLn as $k=>$v){
			$fieldsLn[]=$k.'=:'.$k;
	    $valsLn[':'.$k]=(isset($data[$k]))?$data[$k]:$v;
		}

		$sqlLn=str_replace('{fields}',implode(',', $fieldsLn),$sqlLn);
		$this->setData($sqlLn, $valsLn);

	  //$model=array_merge($model, $modelLn, $data);
	  $model=$this->makeGet('/point/'.$data['p_id']);

    $text=$model['ctr_sysname'].' '.$model['ctr_name'].' '.
					$model['reg_sysname'].' '.$model['reg_name'].' '.
					$model['cit_sysname'].' '.$model['cit_name'].' '.
					$model['ua_sysname'].' '.$model['ua_name'].' '.
					$model['p_sysname'].' '.$model['p_name'];
    $this->storeSearch($model['p_id'], $text);
	  return array('result'=>'success','info'=>'','model'=>$model);
	}
	
	public function postNet($data=array()){
	  if(empty($data)) $data=$this->api->env['_POST'];

		$fields=array();$vals=array();$fieldsLn=array();$valsLn=array();
    $model=array(
      'net_id'=>'',
			'net_sysname'=>'',
		);
		$modelLn=array(
			'net_key'=>'',
			'net_ch1'=>'',
			'net_name'=>'',
			'net_ln'=>$this->api->lang,
		);

		//Редактирование
		if( !empty($data['net_id']) ){
		  $mode='update';
	    $modelBase=$this->makeGet( '/network/'. $data['net_id'] );

			//Если нет такого решиона
	    if(	empty($modelBase)	) unset($data['net_id'],$modelBase);
	    else{
	      $modelBase['net_key']=$modelBase['net_id'];
	      foreach($modelBase as $k=>$v){
		      if(isset($modelLn[$k])) $modelLn[$k]=$v;
				}
				$sql=false;
	      $sqlLn="REPLACE INTO network_name SET net_key=:net_key, net_name=:net_name, net_ln=:ln";
				$valsLn[':net_key']=$data['net_key'];
			}
		}

		//Добавление
	  if( empty($data['net_id']) ){
	  
	    $mode='insert';
	    if( empty($data['net_name']) )
	      //throw_error('net_name expected',500);
				return $this->error('net_name expected');
				

			//$from=$this->getDetectLang()->detect($data['net_name']);
			//if($from!=$this->api->lang){
			if($this->api->lang=='en'){
			  $data['net_name']=translit(netNormalName($data['net_name']));
			  $data['net_name']=ucwords( strtolower($data['net_name']) );
			}

			$data['net_sysname']=translitId( strtolower($data['net_name']) );
			$data['net_id']=$this->getNetId($data['net_name']);

      //Ищу в базе существующее
      $tst=$this->makeGet('/network/'.$data['net_id']);
			if(!empty($tst)) {
			  if(!empty($tst['net_name'])){
          return array('result'=>'fail','info'=>'Network alredy exists','model'=>$tst);
        }
			  $sql=false;
			} elseif($tst===false) {
        $t=$this->getError();
        if( !empty($t) ) return $this->error( $t );
      } else {
			  $sql="INSERT INTO network SET {fields} ";
			}

	    if( !$this->getValid()->network($data) )
				return $this->error('network model validation error');
	    
	    $sqlLn="REPLACE INTO network_name SET {fields} ";
		}

	  $data['net_key']=$data['net_id'];
	  $data['net_ch1']=mb_substr($data['net_name'],0, 1,'utf8');

		if($sql){
		  foreach($model as $k=>$v){
				$fields[]=$k.'=:'.$k;
		    $vals[':'.$k]=(isset($data[$k]))?$data[$k]:$v;
			}

			$sql=str_replace('{fields}',implode(',', $fields),$sql);
		  $this->setData($sql, $vals);
		}

	  foreach($modelLn as $k=>$v){
			$fieldsLn[]=$k.'=:'.$k;
	    $valsLn[':'.$k]=(isset($data[$k]))?$data[$k]:$v;
		}
		$sqlLn=str_replace('{fields}',implode(',', $fieldsLn),$sqlLn);
		$this->setData($sqlLn, $valsLn);

	  $model=$this->makeGet('/network/'.$data['net_id']);

    $text=$model['net_sysname'].' '.$model['net_name'];
    $this->storeSearch($model['net_id'], $text);

	  return array('result'=>'success','info'=>'','model'=>$model);
	}
	
	public function mergeNet($data=array()){
	  $user=$this->getApis()->invoke('user','/byToken/'.$_GET['token']);
	  if(empty($user)) return $this->error('access denied');
	  $user=(array)$user;
	  if( $user['u_type'] != 'geo' )	return $this->error('Access denied');

		if( substr($data['net_from'], 0, 2)!='nt' ) return $this->error('net_from expected network ID only');
		if( substr($data['net_to'], 0, 2)!='nt' ) return $this->error('net_to expected network ID only');
	  $netFrom=$this->makeGet('/network/'.$data['net_from']);
	  if(empty($netFrom)) return $this->error('net_from item "'.$data['net_from'].'" not found');
	  $netTo=$this->makeGet('/network/'.$data['net_to']);
	  if(empty($netTo)) return $this->error('net_to item "'.$data['net_to'].'" not found');
	  $sql="UPDATE point SET p_key_net=:net_to WHERE p_key_net=:net_from";
	  $data=array(':net_from'=>$netFrom['net_id'],':net_to'=>$netTo['net_id']);
	  $this->setData($sql,$data);
	  
	  $sql="UPDATE network SET net_forward=:net_to WHERE net_id=:net_from";
	  $this->setData($sql,$data);
	  return array('result'=>'success','info'=>'');
	}
}
?>